﻿using Renci.SshNet;
using System.Collections.Concurrent;

namespace Tool.Utils
{
    public class SshConnectionPool
    {
        private readonly ConcurrentQueue<SshClient> _pool = new ConcurrentQueue<SshClient>();
        private readonly string _host;
        private readonly int _port;
        private readonly string _username;
        private readonly string _password;
        private readonly int _maxPoolSize;

        public SshConnectionPool(string host, string username, string password, int port = 22, int maxPoolSize = 10)
        {
            _host = host;
            _port = port;
            _username = username;
            _password = password;
            _maxPoolSize = maxPoolSize;
        }

        public SshClient GetConnection()
        {
            if (_pool.TryDequeue(out var client) && client.IsConnected)
            {
                return client;
            }

            var newClient = new SshClient(_host, _username, _password);
            newClient.Connect();
            return newClient;
        }

        public void ReturnConnection(SshClient client)
        {
            if (client.IsConnected && _pool.Count < _maxPoolSize)
            {
                _pool.Enqueue(client);
            }
            else
            {
                client.Disconnect();
                client.Dispose();
            }
        }

        public void Dispose()
        {
            while (_pool.TryDequeue(out var client))
            {
                client.Disconnect();
                client.Dispose();
            }
        }
    }
}
